package main

import (
	"fmt"
	"gitee.com/injoyai/goutil/bytes/coding/json"
	"gitee.com/injoyai/goutil/conv"
	"gitee.com/injoyai/goutil/crypt/md5"
	"gitee.com/injoyai/goutil/g"
	"gitee.com/injoyai/goutil/maps/wait"
	"gitee.com/injoyai/goutil/net/websocket"
	"gitee.com/injoyai/goutil/oss/io"
	"gitee.com/injoyai/goutil/string/logs"
	"time"
)

func main() {

	c, err := websocket.Dial("ws://192.168.10.24:8200/device/issue/write/ws")
	if err != nil {
		logs.Error(err)
		return
	}
	c.Debug()

	AccessID := "3b8a614226a90215"
	AccessSecret := "c4ca4238a0b92382"
	TimeStamp := time.Now().Unix()
	c.Write(conv.Bytes(g.Map{
		"accessID":  "3b8a614226a90215",
		"sign":      md5.Encrypt(fmt.Sprintf("%s#%s#%d", AccessID, AccessSecret, TimeStamp)),
		"timeStamp": TimeStamp,
	}))

	logs.Err(c.Run())

}

func test() {

	url := "ws://192.168.10.24:8200/device/consult/ws?userKey=%s"

	go newConsultClient(url, "1", "2", true)

	newConsultClient(url, "2", "1", true)
}

func newConsultClient(url, key, target string, send bool) {
	w := wait.New(time.Second * 3)
	url = fmt.Sprintf(url, key)
	c, err := websocket.Dial(url)
	if err != nil {
		logs.Err(err)
		return
	}

	c.SetPrintWithASCII()
	c.SetReadWithStartEnd([]byte("{"), []byte("}"))
	c.SetKey(key)
	c.Debug()
	c.SetDealFunc(func(msg *io.Message) {

		m := new(Consult)
		logs.PrintErr(json.Unmarshal(msg.Bytes(), m))

		switch m.Type {
		case "send":

			logs.Debugf("[%s]接收:%s", c.GetKey(), m.Message)

		case "ack":

			w.Done(m.MessageID, nil)
		}

	})
	go func() {
		if !send {
			return
		}
		for i := 0; i < 10; i++ {
			msg := &Consult{
				Type:        "send",
				Target:      target,
				MessageType: "text",
				Message:     conv.String(i),
				MessageID:   conv.String(time.Now().Unix()),
			}
			if _, err := c.Write(conv.Bytes(msg)); err != nil {
				logs.Err(err)
				return
			}

			if _, err := w.Wait(msg.MessageID); err != nil {
				logs.Err(err)
				continue
			}

			logs.Debugf("[%s]发送:%s", c.GetKey(), msg.Message)
			<-time.After(time.Second * 1)
		}
	}()
	logs.Err(c.Run())
}

type Consult struct {
	Type        string `json:"type"`        //消息类型 发送信息(send) 确认信息(ack)
	Target      string `json:"target"`      //目标对象,用户列表的key
	MessageType string `json:"messageType"` //消息类型 图片(image) 文本(text)
	Message     string `json:"message"`     //消息内容
	MessageID   string `json:"messageID"`   //消息id,推荐用当前毫秒
	Date        int64  `json:"-"`           //消息到服务器的时间
}
